<script setup>
import {reactive, ref, watch} from "vue";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  data: {
    type: Object,
    default: () => ({
      id: "",
      name: "",
      status: "",
      remark: "",
      createTime: ""
    })
  }
})

//规则定义
const rules = reactive({
  name: [
    {required: true, message: '名称不能为空', trigger: 'blur'}
  ],
  keyName: [
    {required: true, message: '键名不能为空', trigger: 'blur'}
  ]
})

const emit = defineEmits(['update:visible', 'confirm'])

const isVisible = ref(false)

const dict = ref({
  id: "",
  name: "",
  keyName: "",
  status: "",
  remark: "",
  createTime: ""
})

const formRef = ref(null)

const statusEnum = ref([
  {label: "启用", value: 1},
  {label: "禁用", value: 2}
])

watch(() => props.visible, (newVal) => {isVisible.value = newVal})

watch(() => props.data, (newVal) => {dict.value =  {...newVal}})

const onCancel = () => {
  emit('update:visible', false)
}

const onConfirm = () => {
  if (!formRef) return
  formRef.value.validate(valid => {
    if (valid) {
      emit('confirm', dict.value)
    }
  })
}

const handleDialogClose = () => {
  formRef.value.clearValidate()
  emit('update:visible', false)
}

</script>

<template>
  <el-dialog v-model="isVisible" :title="!dict.id ? '新增' : '编辑'" width="450px" @close="handleDialogClose" :close-on-click-modal="false">
    <el-form ref="formRef" :model="dict" :rules="rules" label-width="68px">
      <el-form-item prop="name" label="名称">
        <el-input v-model="dict.name" placeholder="请输入你的字典名称" maxlength="32" />
      </el-form-item>
      <el-form-item prop="keyName" label="键名">
        <el-input v-model="dict.keyName" placeholder="请输入你的字典键名" maxlength="32" />
      </el-form-item>
      <el-form-item prop="status" label="状态">
        <el-select v-model="dict.status" placeholder="请选择你的字典状态">
          <el-option v-for="(item, index) in statusEnum" :key="index" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="remark" label="备注">
        <el-input type="textarea" maxlength="500" show-word-limit :rows="5" v-model="dict.remark"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" @click="onConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>